<!--
 * @Author: wangshuguang
 * @Date: 2022-02-17 15:37:44
 * @LastEditTime: 2022-04-28 18:24:33
 * @LastEditors: wangshuguang
 * @Description: 代理页面
-->
<template>
  <div v-loading="loading" class="sp-page-main">
    <!-- filter start -->
    <div class="leftLine mg-b-20">流量余额</div>
    <el-row>
      <el-col :span="12">
        <el-card class=" mg-b-20 ">
          <div class="flex-c-sb">
            <span>流量余额：{{ flowInfo.accountFlowBalance || 0 }}</span>
            <el-button type="primary" size="small" @click="editdata">去充值</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div class="leftLine mg-b-20">流量余额记录</div>
    <el-form ref="filterForm" :model="filterForm" label-width="110px" size="small">
      <el-row>
        <el-col :span="12">
          <el-form-item prop="businessNo" label="业务单号">
            <el-input
              v-model="filterForm.businessNo"
              placeholder="请输入"
              clearable
              @keyup.enter.native="submitFilterForm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="payTranNo" label="支付单号">
            <el-input
              v-model="filterForm.payTranNo"
              placeholder="请输入"
              clearable
              @keyup.enter.native="submitFilterForm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="businessType" label="业务类型">
            <el-select v-model="filterForm.businessType" placeholder="请选择" class="width100">
              <el-option label="全部" value="" />
              <el-option label="购买流量余额" value="IN" />
              <el-option label="出售流量余额" value="OUT" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="rechargeStatus" label="状态">
            <el-select v-model="filterForm.rechargeStatus" placeholder="请选择" class="width100">
              <el-option label="全部" value="" />
              <!-- <el-option label="审核中" value="A" /> -->
              <el-option label="交易中" value="W" />
              <el-option label="交易成功" value="S" />
              <el-option label="交易失败" value="F" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="date" label="更新时间">
            <el-date-picker
              v-model="filterForm.date"
              class="width100"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label=" ">
            <el-button type="primary" round @click="submitFilterForm">搜索</el-button>
            <el-button type="primary" round @click="resetFilterForm">重置</el-button>
            <el-button type="text" @click="exportFile">导出excel</el-button>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <!-- filter end -->

    <!-- 表格 start -->
    <div>
      <el-table :data="list" border stripe size="small">
        <el-table-column label="序号" type="index" align="center" width="60">
          <template slot-scope="scope">
            <span>{{ (paginationConfig.page - 1) * paginationConfig.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="businessNo" label="业务单号" width="200" />
        <el-table-column prop="payTranNo" label="支付单号" />
        <el-table-column prop="businessTypeZh" label="业务类型" />
        <el-table-column prop="payeeRoleTypeZh" label="交易对象">
          <template slot-scope="scope">
            <div>{{ scope.row.payee }}</div>
            <div style="color:#9D9D9D">{{ scope.row.payeeRoleTypeZh }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="symbolFlowBalance" label="流量余额(-/+)">
          <template slot-scope="scope">
            <span>{{ scope.row.symbolFlowBalance + scope.row.flowBalance }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="symbolPayAmount" label="交易金额(-/+)">
          <template slot-scope="scope">
            <span>{{ scope.row.symbolPayAmount +'¥'+ scope.row.payAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="rechargeStatusZh" label="状态" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column label="操作" width="50">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="viewData(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <PaginationDirection
        v-if="paginationConfig.total!==0"
        :config="paginationConfig"
        @sizesChange="fetchData"
        @pageChange="fetchData"
      />
    </div>
    <!-- 表格 end -->
    <el-drawer
      :title="infoConfig.title"
      :visible.sync="infoVisible"
      size="60%"
      direction="rtl"
    >
      <detail v-if="infoConfig.type == 'detail' && infoVisible" :info-config="infoConfig" />
      <!-- 机构支付 -->
      <payAgt v-else-if="infoConfig.type == 'payAgt' && infoVisible" :info-config="infoConfig" @close="close" @sucClose="sucClose" />
    </el-drawer>
  </div>
</template>

<script>
import detail from './components/detail.vue'
import payAgt from './components/payAgt.vue'
import { mapGetters } from 'vuex'
import { dateFtt } from '@/utils'
import dayjs from 'dayjs'
import {
  agtGetFlowBalance,
  agtGetFlowBalanceRecord,
  tenInDetail,
  tenOutDetail,
  tenantExport
} from '@/api/sp/flow'

export default {
  components: {
    detail, payAgt
  },
  props: {
    tabName: {
      type: String,
      default: 'search'
    }
  },
  data() {
    return {
      infoVisible: false,
      infoConfig: {
        title: '',
        data: {}
      },
      flowInfo: {},
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      spPackageOptions: [],
      tagOptions: [],
      userListOptions: [],
      // 状态
      loading: false,
      // 数据
      list: [],
      filterForm: {
        name: null,
        serial: null,
        userSuffix: null,
        spPackageId: null,
        tags: [],
        creator: null
      },
      allFilterIds: {
        tags: [] // 所有tags key
      },
      lastFilterIds: {
        tags: [] // 上次tags key
      }
    }
  },
  computed: {
    ...mapGetters(['sidebarMenus', 'activeSidebarMenusCode', 'userInfo', 'agentFlow', 'spInfo', 'fileBaseUrl'])
  },
  mounted() {
    console.log('this.spInfo123', this.spInfo)
    this.fetchData()
    this.getFlowData()
    this.autoShowPay()
  },
  methods: {
    autoShowPay() {
      const { showPay } = this.$route.query
      if (showPay) {
        this.editdata()
      }
    },
    exportFile() {
      if (!this.spInfo.syncTmpServicerId) {
        console.warn('不存在同步数据 syncTmpServicerId')
        return
      }
      const obj = {
        userId: this.spInfo.syncTmpServicerId,
        'pageNum': this.paginationConfig.page,
        'pageSize': this.paginationConfig.pageSize,
        'businessNo': this.filterForm.businessNo,
        'payTranNo': this.filterForm.payTranNo,
        'businessType': this.filterForm.businessType,
        'rechargeStatus': this.filterForm.rechargeStatus
      }
      if (this.filterForm.date && this.filterForm.date.length) {
        obj.updTimeBegin = dateFtt('yyyy-MM-dd 00:00:00', this.filterForm.date[0])
        obj.updTimeEnd = dateFtt('yyyy-MM-dd 23:59:59', this.filterForm.date[1])
      }
      console.log('obj', obj)
      tenantExport({
        ...obj,
        'isInclude': true,
        'fieldList': [
          // {
          //   'fieldName': 'id',
          //   'fieldShowName': '序号',
          //   'fieldOrderNumber': 1
          // },
          {
            'fieldName': 'businessNo',
            'fieldShowName': '业务单号',
            'fieldOrderNumber': 1
          },
          {
            'fieldName': 'payTranNo',
            'fieldShowName': '支付单号',
            'fieldOrderNumber': 2
          },
          {
            'fieldName': 'businessType',
            'fieldShowName': '业务类型',
            'fieldOrderNumber': 3
          },
          {
            'fieldName': 'payer',
            'fieldShowName': '交易对象',
            'fieldOrderNumber': 4
          },
          {
            'fieldName': 'flowBalance',
            'fieldShowName': '流量余额(-/+)',
            'fieldOrderNumber': 5
          },
          {
            'fieldName': 'payAmount',
            'fieldShowName': '交易金额(-/+)',
            'fieldOrderNumber': 6
          },
          {
            'fieldName': 'rechargeStatus',
            'fieldShowName': '状态',
            'fieldOrderNumber': 7
          },
          {
            'fieldName': 'remark',
            'fieldShowName': '备注',
            'fieldOrderNumber': 8
          },
          {
            'fieldName': 'updateTime',
            'fieldShowName': '更新时间',
            'fieldOrderNumber': 9
          }
        ]
      }).then(res => {
        console.log('下载文件', res)
        this.$downloadFile(res.data, `流量余额记录-${dayjs(new Date()).format('YYYY年MM月DD日 HH-mm-ss')}`)
      })
    },
    sucClose() {
      this.infoVisible = false
      this.fetchData()
      this.getFlowData()
    },
    close() {
      this.infoVisible = false
    },
    getFlowData() {
      if (!this.spInfo.syncTmpServicerId) {
        console.warn('不存在同步数据 syncTmpServicerId')
        return
      }
      agtGetFlowBalance({ id: this.spInfo.syncTmpServicerId }).then(res => {
        console.log('res', res)
        this.flowInfo = res.data
      })
    },
    editdata(data) {
      if (!this.spInfo.syncTmpServicerId) {
        console.warn('不存在同步数据 syncTmpServicerId')
        return
      }
      this.infoConfig = {
        type: 'payAgt',
        title: '代理充值流量余额',
        data
      }
      this.infoVisible = true
    },
    viewData(data) {
      const obj = {
        businessNo: data.businessNo,
        id: data.id
      }
      // const fun = data.businessType == 'IN' ? tenInDetail : tenOutDetail
      // 代理全部使用out详情
      tenOutDetail(obj).then(res => {
        console.log('res', res)
        const detail = res.data
        this.infoConfig = {
          type: 'detail',
          title: '详情',
          data: {
            ...detail,
            imgArr: [detail.atta1, detail.atta2, detail.atta3]
          }
        }
        this.infoVisible = true
      })
    },
    /**
     * 数据组
     */
    // 获取列表
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      if (!this.spInfo.syncTmpServicerId) {
        console.warn('不存在同步数据 syncTmpServicerId')
        return
      }
      // 请求参数
      const params = Object.assign({
        userId: this.spInfo.syncTmpServicerId,
        pageNum: page,
        pageSize
      }, this.filterForm)
      // 清除多余字段
      params.tags = params.tags.includes('') ? [] : params.tags
      for (const key in params) {
        if (this.$isNull(params[key]) || Array.isArray(params[key]) && params[key].length === 0) delete params[key]
      }
      if (params.date && params.date.length && params.date[0]) {
        params.updTimeBegin = dateFtt('yyyy-MM-dd 00:00:00', params.date[0])
        params.updTimeEnd = dateFtt('yyyy-MM-dd 23:59:59', params.date[1])
        delete params.date
      }
      // 请求
      this.loading = true
      agtGetFlowBalanceRecord(params)
        .then(res => {
          this.list = res.data.list.map(v => ({
            ...v,
            payTranNo: v.payTranNo || '-',
            updateTime: dateFtt('yyyy-MM-dd hh:mm:ss', new Date(v.updateTime))
          }))
          this.paginationConfig.total = res.data.total
          this.paginationConfig.page = params.pageNum
        })
        .finally(() => {
          this.loading = false
        })
    },

    /**
     * 按钮组
     */
    // 查询
    submitFilterForm() {
      this.fetchData(1)
    },

    // 重置
    resetFilterForm() {
      this.$refs.filterForm.resetFields()
    },

    /**
     * 状态组
     */
    // 多选改变
    selectMultipleChange(val, type) {
      const lastVal = this.lastFilterIds[type]
      if (val.includes('')) {
        this.filterForm[type] = this.allFilterIds[type]
      }
      if (lastVal.includes('') && !val.includes('')) {
        this.filterForm[type] = []
      }
      if (lastVal.includes('') && val.includes('')) {
        val.splice(
          val.findIndex((v) => v === ''),
          1
        )
        this.filterForm[type] = val
      }
      if (!lastVal.includes('') && !val.includes('')) {
        if (val.length === this.allFilterIds[type].length - 1) {
          this.filterForm[type] = [''].concat(val)
        }
      }
      this.lastFilterIds[type] = this.filterForm[type]
    }
    /**
     * 方法组
     */

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.sp-page-main {
  margin-top: 10px;
}
</style>
